/*
 * Copyright (C) 2020  Prasoon Joshi
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package controllers

import java.util.UUID

import javax.inject._
import models._
import play.api.libs.json.{JsObject, JsString, JsValue, Json}
import play.api.mvc._

import configuration.QoreComponentRegistry._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject()(messagesAction: MessagesActionBuilder,
                               cc: ControllerComponents) extends AbstractController(cc) {

  /**
   * Create an Action to render an HTML page.
   *
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index() = messagesAction { implicit request: MessagesRequest[AnyContent] =>
    Ok(views.html.index
    (FormItem.itemForm))
  }

//  import sangria.renderer.SchemaRenderer
//  def graphqlSchema() = Action {implicit request: Request[AnyContent] =>
//    Ok(SchemaRenderer.renderSchema(SchemaDefinition.schema))
//  }

  def itemForm() = messagesAction { implicit request: MessagesRequest[AnyContent] =>
    //val itemData = itemForm.bindFromRequest().get
    FormItem.itemForm.bindFromRequest.fold(
      formWithErrors => {
        //TODO: Add a BadRequest(views.html.user(formWithErrors))
        // This would ensure that users is redirected to the same form with errors highlighted.
        BadRequest
      },
      itemData => {
        val newItem = ItemData(UUID.randomUUID(), itemData.title)
        //TODO: Save the 'newItem'
        //TODO: RedirectAfterPOST - solves the duplicate form submission issue.
      }
    )
    Ok(views.html.index(FormItem.itemForm))
  }

  def parseVariables(vars: String) =
    if (vars.trim == "" || vars.trim == "null") Json.obj() else Json.parse(vars).as[JsObject]

  def graphQl = Action.async(parse.json) { implicit  request: Request[JsValue] =>

    import scala.concurrent.ExecutionContext.Implicits.global
    queryServer.fetchQueryResult(request.body)
  }

}
